<template>
    <div class="carousel-form-container">
        <!-- 页面头部 -->
        <div class="page-header">
            <div class="header-content">
                <div class="header-left">
                    <h2>{{ isEdit ? '编辑轮播' : '新增轮播' }}</h2>
                </div>
                <div class="header-right">
                    <el-button @click="handleCancel">
                        <el-icon><ArrowLeft /></el-icon>
                        返回
                    </el-button>
                </div>
            </div>
        </div>

        <!-- 表单内容 -->
        <div class="form-content">
            <el-card shadow="never" class="form-card">
                <el-form
                    ref="carouselFormRef"
                    :model="formData"
                    :rules="formRules"
                    label-width="120px"
                    class="carousel-form"
                >
                    <!-- 中英文 -->
                    <el-form-item label="中英文:" prop="language">
                        <el-select v-model="formData.language" placeholder="请选择" style="width: 200px">
                            <el-option label="中文" value="zh-CN" />
                            <el-option label="英文" value="en" />
                        </el-select>
                    </el-form-item>

                    <!-- 标题 -->
                    <el-form-item label="标题:" prop="title">
                        <el-input
                            v-model="formData.title"
                            placeholder="输入轮播标题"
                            style="width: 300px"
                        />
                    </el-form-item>

                    <!-- URL -->
                    <el-form-item label="URL:" prop="url">
                        <el-input
                            v-model="formData.url"
                            placeholder="输入URL"
                            style="width: 300px"
                        />
                    </el-form-item>

                    <!-- 排序顺序 -->
                    <el-form-item label="排序顺序:" prop="sortOrder">
                        <el-input-number
                            v-model="formData.sortOrder"
                            :min="0"
                            :max="999"
                            placeholder="输入排序顺序"
                            style="width: 200px"
                        />
                    </el-form-item>

                    <!-- 状态 -->
                    <el-form-item label="状态:" prop="status">
                        <el-radio-group v-model="formData.status">
                            <el-radio :value="1">启用</el-radio>
                            <el-radio :value="0">禁用</el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <!-- 封面图 -->
                    <el-form-item label="封面图:" prop="imageUrl">
                        <el-upload
                            class="cover-uploader"
                            :show-file-list="false"
                            :on-success="handleCoverSuccess"
                            :before-upload="beforeCoverUpload"
                            action="#"
                        >
                            <img v-if="formData.imageUrl" :src="formData.imageUrl" class="cover-image" />
                            <el-icon v-else class="cover-uploader-icon"><Plus /></el-icon>
                        </el-upload>
                        <div class="form-hint">封面尺寸宽100*80</div>
                    </el-form-item>

                    <!-- 内容 -->
                    <el-form-item label="内容:" prop="content">
                        <div class="rich-editor-container">
                            <Toolbar
                                style="border-bottom: 1px solid #ccc"
                                :editor="editorRef"
                                :defaultConfig="toolbarConfig"
                                :mode="mode"
                            />
                            <Editor
                                style="height: 300px; overflow-y: hidden;"
                                v-model="formData.content"
                                :defaultConfig="editorConfig"
                                :mode="mode"
                                @onCreated="handleCreated"
                            />
                        </div>
                    </el-form-item>

                    <!-- 操作按钮 -->
                    <el-form-item>
                        <el-button type="primary" @click="handleSubmit">保存</el-button>
                        <el-button @click="handleCancel">取消</el-button>
                    </el-form-item>
                </el-form>
            </el-card>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onBeforeUnmount, shallowRef } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ArrowLeft, Plus } from '@element-plus/icons-vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import '@wangeditor/editor/dist/css/style.css';
import { createBanner, updateBanner, getBannerById } from '@/api/system/banner';

const route = useRoute();
const router = useRouter();

// 判断是否为编辑模式
const isEdit = computed(() => !!route.params.id);

// 表单引用
const carouselFormRef = ref();

// 编辑器实例
const editorRef = shallowRef();
const mode = 'default'; // 或 'simple'

// 表单数据
const formData = reactive({
    id: '',
    language: '',
    title: '',
    url: '',
    sortOrder: 0,
    status: 1,
    content: '',
    imageUrl: 'http://www.baidu.com'
});

// 编辑器配置
const toolbarConfig = {
    toolbarKeys: [
        'headerSelect',
        'blockquote',
        '|',
        'bold',
        'underline',
        'italic',
        {
            key: 'group-more-style',
            title: '更多样式',
            iconSvg: '<svg viewBox="0 0 1024 1024"><path d="M204.8 505.6m-76.8 0a76.8 76.8 0 1 0 153.6 0 76.8 76.8 0 1 0-153.6 0Z"></path><path d="M505.6 505.6m-76.8 0a76.8 76.8 0 1 0 153.6 0 76.8 76.8 0 1 0-153.6 0Z"></path><path d="M806.4 505.6m-76.8 0a76.8 76.8 0 1 0 153.6 0 76.8 76.8 0 1 0-153.6 0Z"></path></svg>',
            menuKeys: ['through', 'code', 'sup', 'sub', 'clearStyle']
        },
        'color',
        'bgColor',
        '|',
        'fontSize',
        'fontFamily',
        'lineHeight',
        '|',
        'bulletedList',
        'numberedList',
        'todo',
        {
            key: 'group-justify',
            title: '对齐',
            iconSvg: '<svg viewBox="0 0 1024 1024"><path d="M768 793.6v102.4H51.2v-102.4h716.8z m204.8-230.4v102.4H51.2v-102.4h921.6z m-204.8-230.4v102.4H51.2v-102.4h716.8z m204.8-230.4v102.4H51.2v-102.4h921.6z"></path></svg>',
            menuKeys: ['justifyLeft', 'justifyRight', 'justifyCenter', 'justifyJustify']
        },
        {
            key: 'group-indent',
            title: '缩进',
            iconSvg: '<svg viewBox="0 0 1024 1024"><path d="M0 64h1024v128H0z m384 192h640v128H384z m0 192h640v128H384z m0 192h640v128H384zM0 832h1024v128H0z m0-128V320l256 192z"></path></svg>',
            menuKeys: ['indent', 'delIndent']
        },
        '|',
        'emotion',
        'insertLink',
        {
            key: 'group-image',
            title: '图片',
            iconSvg: '<svg viewBox="0 0 1024 1024"><path d="M959.877 128l0.123 0.123v767.775l-0.123 0.122H64.102l-0.122-0.122V128.123l0.122-0.123h895.775zM960 64H64C28.795 64 0 92.795 0 128v768c0 35.205 28.795 64 64 64h896c35.205 0 64-28.795 64-64V128c0-35.205-28.795-64-64-64zM832 288.01c0 53.023-42.988 96.01-96.01 96.01s-96.01-42.987-96.01-96.01S682.967 192 735.99 192 832 234.988 832 288.01zM896 832H128V704l224.01-168 96.01 72 192.01-144 255.97 240z"></path></svg>',
            menuKeys: ['insertImage', 'uploadImage']
        },
        {
            key: 'group-video',
            title: '视频',
            iconSvg: '<svg viewBox="0 0 1024 1024"><path d="M981.184 160.096C837.568 139.456 678.848 128 512 128S186.432 139.456 42.816 160.096C15.296 267.808 0 386.848 0 512s15.264 244.16 42.816 351.904C186.464 884.544 345.152 896 512 896s325.568-11.456 469.184-32.096C1008.704 756.192 1024 637.152 1024 512s-15.264-244.16-42.816-351.904zM384 704V320l320 192-320 192z"></path></svg>',
            menuKeys: ['insertVideo', 'uploadVideo']
        },
        'insertTable',
        'codeBlock',
        'divider',
        '|',
        'undo',
        'redo',
        '|',
        'fullScreen'
    ]
};

const editorConfig = {
    placeholder: '请输入内容...',
    MENU_CONF: {
        uploadImage: {
            server: '/api/upload-image',
            fieldName: 'file',
            maxFileSize: 2 * 1024 * 1024, // 2M
            allowedFileTypes: ['image/*'],
            customInsert(res: any, insertFn: any) {
                // res 即服务端的返回结果
                const { url } = res.data;
                insertFn(url);
            }
        },
        uploadVideo: {
            server: '/api/upload-video',
            fieldName: 'file',
            maxFileSize: 10 * 1024 * 1024, // 10M
            allowedFileTypes: ['video/*'],
            customInsert(res: any, insertFn: any) {
                const { url } = res.data;
                insertFn(url);
            }
        }
    }
};

// 表单验证规则
const formRules = {
    language: [
        { required: true, message: '请选择中英文', trigger: 'change' }
    ],
    title: [
        { required: true, message: '请输入标题', trigger: 'blur' },
    ],
    url: [
        { required: true, message: '请输入URL', trigger: 'blur' },
    ],
    sortOrder: [
        { required: true, message: '请输入排序顺序', trigger: 'blur' }
    ],
    status: [
        { required: true, message: '请选择状态', trigger: 'change' }
    ],
    // imageUrl: [
    //     { required: true, message: '请上传封面图', trigger: 'change' }
    // ],
    content: [
        { required: true, message: '请输入内容', trigger: 'blur' }
    ]
};

// 封面图上传处理
const handleCoverSuccess = (response: any, file: any) => {
    formData.imageUrl = URL.createObjectURL(file.raw);
};

const beforeCoverUpload = (file: any) => {
    const isImage = file.type.startsWith('image/');
    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!isImage) {
        ElMessage.error('只能上传图片文件!');
        return false;
    }
    if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB!');
        return false;
    }
    return true;
};

// 编辑器创建完成
const handleCreated = (editor: any) => {
    editorRef.value = editor;
};

// 提交表单
const handleSubmit = async () => {
    try {
        await carouselFormRef.value.validate();
        
        // 准备提交数据
        const submitData = {
            language: formData.language,
            title: formData.title,
            url: formData.url,
            sortOrder: formData.sortOrder,
            status: formData.status,
            content: formData.content,
            imageUrl: formData.imageUrl
        };
        
        if (isEdit.value) {
            // 编辑模式
            await updateBanner(formData.id, submitData);
            ElMessage.success('编辑成功');
        } else {
            // 新增模式
            await createBanner(submitData);
            ElMessage.success('新增成功');
        }
        
        // 返回列表页
        router.push('/carousel-list');
    } catch (error) {
        console.error('提交失败:', error);
        ElMessage.error('提交失败，请检查表单内容');
    }
};

// 取消操作
const handleCancel = () => {
    ElMessageBox.confirm(
        '确定要离开吗？未保存的内容将丢失。',
        '确认离开',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        router.go(-1);
    }).catch(() => {
        // 用户取消
    });
};

// 加载编辑数据
const loadEditData = async (id: string) => {
    try {
        const response = await getBannerById(id);
        if (response.data) {
            const data = response.data;
            formData.id = data.id;
            formData.language = data.language;
            formData.title = data.title;
            formData.url = data.url;
            formData.sortOrder = data.sortOrder;
            formData.status = data.status;
            formData.content = data.content;
            // formData.imageUrl = data.imageUrl;
            formData.imageUrl = data.imageUrl || 'http://www.baidu.com';
        }
    } catch (error) {
        console.error('加载数据失败:', error);
        ElMessage.error('加载数据失败');
    }
};

// 页面初始化
onMounted(() => {
    if (isEdit.value) {
        // 编辑模式，加载数据
        const id = route.params.id as string;
        loadEditData(id);
    }
});

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value;
    if (editor == null) return;
    editor.destroy();
});
</script>

<style scoped>
.carousel-form-container {
    padding: 20px;
    background-color: #f5f5f5;
    min-height: 100vh;
}

/* 页面头部 */
.page-header {
    margin-bottom: 20px;
}

.header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-left h2 {
    margin: 0;
    color: #303133;
    font-size: 24px;
    font-weight: 600;
}

.header-right {
    display: flex;
    align-items: center;
    gap: 12px;
}

/* 表单内容 */
.form-content {
    max-width: 800px;
}

.form-card {
    border-radius: 8px;
}

.carousel-form {
    padding: 20px;
}

.form-hint {
    color: #909399;
    font-size: 12px;
    margin-top: 5px;
    margin-left: 8px;
}

/* 封面图上传 */
.cover-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 100px;
    height: 80px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.cover-uploader:hover {
    border-color: #409eff;
}

.cover-uploader-icon {
    font-size: 28px;
    color: #8c939d;
}

.cover-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

/* 富文本编辑器 */
.rich-editor-container {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    overflow: hidden;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .carousel-form-container {
        padding: 10px;
    }
    
    .form-content {
        max-width: 100%;
    }
    
    .carousel-form {
        padding: 15px;
    }
    
    .editor-toolbar {
        flex-direction: column;
        align-items: flex-start;
    }
    
    .toolbar-group {
        margin-bottom: 8px;
    }
}
</style>
